package com.example.layui.controller;

import com.example.layui.mapper.RoleMapper;
import com.example.layui.pojo.Role;
import com.example.layui.pojo.UserVo;
import com.example.layui.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
public class RoleController {

    @Resource
    RoleMapper roleMapper;

    @RequestMapping("/demo/table/role/")
    @ResponseBody
    public ResponseResult users(Role role, Integer page, Integer limit) {
        ResponseResult responseResult = new ResponseResult(0, ""
                , roleMapper.count(role)
                , roleMapper.queryByPage(role, (page - 1) * limit, limit));
        return responseResult;
    }

    @RequestMapping("/addRole")
    @ResponseBody
    public ResponseResult addRole(Role role){
        int result=roleMapper.addRole(role);
        if(result>0){
            return new ResponseResult(0,"添加成功","");
        }
        return new ResponseResult(1,"添加失败","");
    }

    @RequestMapping("/deleteRoles")
    @ResponseBody
    public ResponseResult deleteRoles(@RequestBody List<Role> roles){
        //删除角色role 以及关联的表user_role,role_menu
        for (Role role : roles){
            //删除user_role
            roleMapper.delUserRole(role.getId());
            //删除role_menu
            roleMapper.delRoleMenu(role.getId());
            //删除role
            roleMapper.delRole(role.getId());
        }
        return new ResponseResult(0,"删除成功","");
    }

    @RequestMapping("/deleteRoleById")
    @ResponseBody
    public ResponseResult deleteRoleById(int id){
        //删除角色role 以及关联的表user_role,role_menu
        //删除user_role
        roleMapper.delUserRole(id);
        //删除role_menu
        roleMapper.delRoleMenu(id);
        //删除role
        roleMapper.delRole(id);
        return new ResponseResult(0,"删除成功","");
    }

    //拿数据到修改页面
    @RequestMapping("/user/role/update")
    public String updateRole(Model model,int id){
        Role role=roleMapper.queryRoleById(id);
        model.addAttribute("role",role);
        return "views/user/role/roleform2";
    }

    @RequestMapping("/updateRole")
    @ResponseBody
    public ResponseResult updateRole(Role role){
        int result=roleMapper.updateRole(role);
        return new ResponseResult(0,"修改成功","");
    }


}
